const redis = require("redis");
const _ = require("lodash");
const bluebird = require("bluebird");
const config = require("./config");
const util = require("./util");

bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);

// redis初始化
const client = redis.createClient(config.redis);

module.exports = Object.assign(client, {
  async lock(key, expire = 3) {
    const result = await BaaS.redis.saddAsync(key, 1);
    await BaaS.redis.expireAsync(key, expire);
    return result;
  },
  async unlock(key) {
    const result = await BaaS.redis.delAsync(key);
    return result;
  },
  async delAll(key) {
    const keys = await BaaS.redis.keysAsync(key);
    for (const key in keys) {
      await BaaS.redis.delAsync(keys[key]);
    }
  },
  async listAdd(key) {
    const keys = await BaaS.redis;
  },
  async cache(key, value, expire = 3600 * 24) {
    if (_.isUndefined(value)) {
      const cache = await BaaS.redis.getAsync(key);
      if (util.isStrToJson(cache)) {
        return JSON.parse(cache);
      } else {
        return cache;
      }
    }

    const result = await BaaS.redis.setAsync(
      key,
      util.isJsonToStr(value) ? JSON.stringify(value) : value
    );
    await BaaS.redis.expireAsync(key, expire);
    return result;
  }
});
